package edu.ynu.se.xiecheng.achitectureclass.common.utils.test;

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class FBoxTokenFetcher {

    public static String fetchToken() {
        // API URL
        String url = "https://fbox360.com/idserver/core/connect/token";

        // 请求头配置
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 请求体配置
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("scope", "fbox");
        requestBody.put("client_id", "68db2e8bda8d47b5b5db7eaf71c7dcdd");
        requestBody.put("client_secret", "76dc724c95004acab25482d344dab407");
        requestBody.put("grant_type", "client_credentials");

        // 将请求体转换为表单格式
        StringBuilder formBody = new StringBuilder();
        requestBody.forEach((key, value) -> formBody.append(key).append("=").append(value).append("&"));
        formBody.deleteCharAt(formBody.length() - 1); // 移除最后一个 "&"

        HttpEntity<String> requestEntity = new HttpEntity<>(formBody.toString(), headers);

        // 发送 POST 请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);

        // 解析响应
        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> responseBody = response.getBody();
            assert responseBody != null;
            return (String) responseBody.get("access_token");
        } else {
            throw new RuntimeException("Failed to fetch token. Status code: " + response.getStatusCode());
        }
    }

    public static void main(String[] args) {
        String token = fetchToken();
        System.out.println("Access Token: " + token);
    }
}

